package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.json.JSONUtil;
import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.framework.config.properties.AliIoTConfigProperties;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 设备管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-10-14
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private AliIoTConfigProperties aliIoTConfigProperties;

    @Autowired
    private Client client;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 查询设备管理
     * 
     * @param id 设备管理主键
     * @return 设备管理
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备管理列表
     * 
     * @param device 设备管理
     * @return 设备管理
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备管理
     * 
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备管理
     * 
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备管理
     * 
     * @param ids 需要删除的设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备管理信息
     * 
     * @param id 设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 从物联网平台同步产品列表
     */
    @Override
    public void syncProductList() {
        //查询所有产品
        QueryProductListRequest request = new QueryProductListRequest();
        //设置请求参数
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        request.setCurrentPage(1);
        request.setPageSize(100);
        //调用第三方接口查询产品列表
        QueryProductListResponse response;
        try {
            response = client.queryProductList(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询产品，同步失败");
        }

        // 判断，如果数据为空，则中断请求
        if(!response.getBody().success){
            throw new BaseException("物联网接口 - 查询产品，调用失败");
        }

            //将产品列表保存到redis中
            redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST, JSONUtil.toJsonStr(response.getBody().getData().getList().getProductInfo()));

    }

    /**
     * 从缓存中获取产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        String result = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST);

        return JSONUtil.toList(result, ProductVo.class);

    }

    /**
     * 注册设备
     *
     * @param deviceDto
     */
    @Override
    public void registerDevice(DeviceDto deviceDto) {
        //判断设备名称是否重复
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getDeviceName, deviceDto.getDeviceName());
        if(deviceMapper.selectCount(queryWrapper) > 0){
            throw new BaseException("设备名称重复，请重新输入");
        }
        //在iot平台中创建设备
        //使用第三方接口创建设备 RegisterDeviceRequest
            RegisterDeviceRequest request = deviceDto.getRegisterDeviceRequest();
        //设置请求参数iotInstanceId 实例ID
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        RegisterDeviceResponse productResponse;
        try {
           productResponse = client.registerDevice(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 注册设备，调用失败");
        }

        //判断是否成功
        if(!productResponse.getBody().success){
            throw new BaseException(productResponse.getBody().getErrorMessage());
        }

        //此时设备创建成功 获取设备信息 主要是为了获取 产品名称
        QueryProductRequest queryProductRequest = new QueryProductRequest();
        queryProductRequest.setProductKey(deviceDto.getProductKey());
        queryProductRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryProductResponse queryProductResponse;
        try {
            queryProductResponse = client.queryProduct(queryProductRequest);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询产品，调用失败");
        }
        // 判断接口是否调通
        if(!queryProductResponse.getBody().success){
            throw new BaseException("物联网接口 - 查询产品，调用失败");
        }
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        device.setProductName(queryProductResponse.getBody().getData().productName);


        // 物理位置
        if(device.getLocationType().equals(0)) {
            device.setPhysicalLocationType(-1);
        }
        // 补全设备id 在创建设备的时候已经返回了
        device.setIotId(productResponse.getBody().getData().getIotId());
        device.setCreateTime(new Date());

        // 保存到数据库中
        try {
            deviceMapper.insertDevice(device);
        } catch (Exception e) {
            //出现异常说明插入失败 此时要删除 iot平台中的设备
            DeleteDeviceRequest deleteDeviceRequest = new DeleteDeviceRequest();
            // 设置参数 参考iot 平台文档
            deleteDeviceRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
            deleteDeviceRequest.setProductKey(deviceDto.getProductKey());
            deleteDeviceRequest.setDeviceName(deviceDto.getDeviceName());
            deleteDeviceRequest.setIotId(productResponse.getBody().getData().getIotId());
            try {
                client.deleteDevice(deleteDeviceRequest);
            } catch (Exception ex) {
                throw new BaseException("物联网接口 - 删除设备，调用失败");
            }
            throw new BaseException("该老人/位置已绑定该产品，请重新选择");
        }
    }

    /**
     * @param deviceDto
     * @return
     */
    @Override
    public DeviceVo queryDeviceDetail(DeviceDto deviceDto) {
        //1.查询iot 平台设备详情
        QueryDeviceDetailRequest request = new QueryDeviceDetailRequest();
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        request.setProductKey(deviceDto.getProductKey());
        request.setIotId(deviceDto.getIotId());
        QueryDeviceDetailResponse response;
        try {
            response = client.queryDeviceDetail(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询设备详情，调用失败");
        }
        if(!response.getBody().success){
            throw new BaseException("物联网接口 - 查询设备详情，调用失败");
        }
        //查询数据库表中的数据
        Device device=deviceMapper.selectOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId,deviceDto.getIotId()));
        DeviceVo deviceVo = BeanUtil.toBean(device, DeviceVo.class);

        // 合并
        QueryDeviceDetailResponseBody.QueryDeviceDetailResponseBodyData data = response.getBody().getData();
        BeanUtil.copyProperties(data, deviceVo, CopyOptions.create().ignoreNullValue());
        return deviceVo;
    }

    /**
     * 查询物模型
     *
     * @param request
     * @return
     */
    @Override
    public AjaxResult queryThingModelPublished(QueryThingModelPublishedRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryThingModelPublishedResponse response;
        try {
            response = client.queryThingModelPublished(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询物模型，调用失败");
        }
        if(!response.getBody().success){
            throw new BaseException("物联网接口 - 查询物模型，调用失败");
        }
        return  AjaxResult.success(response.getBody().data);

    }

    /**
     * 查询设备属性
     *
     * @param request
     * @return
     */
    @Override
    public AjaxResult queryDevicePropertyStatus(QueryDevicePropertyStatusRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryDevicePropertyStatusResponse response;
        try {
            response = client.queryDevicePropertyStatus(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询设备属性，调用失败");
        }
        if(!response.getBody().success){
            throw new BaseException("物联网接口 - 查询设备属性，调用失败");
        }
        return  AjaxResult.success(response.getBody().data) ;
    }

    /**
     * 修改设备管理
     *
     * @param deviceDto 设备管理
     * @return 结果
     */
    @Override
    @Transactional (rollbackFor = Exception.class)
    public int updateDeviceDto(DeviceDto deviceDto) {
        BatchUpdateDeviceNicknameRequest request = new BatchUpdateDeviceNicknameRequest();
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        List<BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo> list=new ArrayList<>();
        BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo deviceNicknameInfo = new BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo().setIotId(deviceDto.getIotId()).setNickname(deviceDto.getNickname());
        //封装数据条件
        deviceNicknameInfo.setIotId(deviceDto.getIotId());
        deviceNicknameInfo.setNickname(deviceDto.getNickname());
        list.add(deviceNicknameInfo);

        request.setDeviceNicknameInfo(list);
         BatchUpdateDeviceNicknameResponse response;
        try {
           response= client.batchUpdateDeviceNickname(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 修改设备，调用失败");
        }
        if(!response.getBody().success){
            throw new BaseException("物联网接口 - 修改设备，调用失败");
        }
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        boolean flag = update(device, Wrappers.<Device>lambdaUpdate().eq(Device::getIotId, device.getIotId()));
        return   flag? 1:0;
    }

    /**
     * 删除设备
     *
     * @param request
     * @return
     */
    @Override
    public int deleteDevice(DeleteDeviceRequest request) {
           request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
           DeleteDeviceResponse response;
           try {
               response = client.deleteDevice(request);
           } catch (Exception e) {
               throw new BaseException("物联网接口 - 删除设备，调用失败");
           }
           if(!response.getBody().success){
               throw new BaseException("物联网接口 - 删除设备，调用失败");
           }
           //删除数据库中的数据
          return deviceMapper.delete(Wrappers.<Device>lambdaQuery().eq(Device::getIotId,request.getIotId()));

    }
}
